﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Reflection;

namespace Utility.Data
{
    /// <summary>
    /// Hashtable帮助类
    /// </summary>
    public class HashtableHelper
    {
        public static string HashtableToXml(Hashtable ht)
        {
            StringBuilder xml = new StringBuilder("<root>");
            xml.Append(HashtableToNode(ht));
            xml.Append("</root>");
            return xml.ToString();
        }

        private static string HashtableToNode(Hashtable ht)
        {
            StringBuilder xml = new StringBuilder("");
            foreach (string key in ht.Keys)
            {
                object value = ht[key];
                xml.Append("<").Append(key).Append(">").Append(value).Append("</").Append(key).Append(">");
            }
            xml.Append("");
            return xml.ToString();
        }

        public static string IListToXML(IList<Hashtable> htList)
        {
            StringBuilder xml = new StringBuilder("<root>");
            foreach (Hashtable ht in htList)
            {
                xml.Append(HashtableToNode(ht));
            }
            xml.Append("</root>");
            return xml.ToString();
        }

        /// <summary>
        /// 实体类Model转Hashtable(反射)
        /// </summary>
        public static Hashtable GetModelToHashtable<T>(T model)
        {
            Hashtable ht = new Hashtable();
            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (PropertyInfo pi in properties)
            {
                string key = pi.Name;
                ht[key] = pi.GetValue(model, null);
            }
            return ht;
        }
        /// <summary>
        /// 字符串 分割转换 Hashtable  name=cnmmmss|age=43$name=lin|age=12
        /// </summary>
        public static Hashtable KeysToHashtable(string input)
        {
            Hashtable ht = new Hashtable();
            if (!String.IsNullOrEmpty(input))
            {
                string[] arr = input.Split('|');
                foreach (string m in arr)
                {
                    if (m.Length > 0)
                    {
                        string[] value = m.Split('=');
                        ht[value[0]] = value[1];
                    }
                }
            }
            return ht;
        }
    }
}